<template>
	<view class="containerbox">
		<view class="containerbox">
			<view class="containerbox">
				<template v-if="!item.answerFile">
					<view class="flex items-center justify-center" style="padding-top: 210rpx;">
						<view 
							class="px-100 text-center font-weight-700 relative" 
							:style="{'font-size': wordlist.length > 1 ? '48rpx': '80rpx'}" 
							@click="playAudio(item.voiceFile?.url)">
							{{item.word.replace(/\s+/g, '')}}
							<!-- {{item.word}} -->
							<!-- {{wordlist}} -->
							<view class="ml-10" style="display: inline-block;" v-if="!item.soundmark">
								<c_trumpet :play="isPlayWord"/>
							</view>
						</view>
					</view>
					<view class="flex flex-column items-center" v-if="item.soundmark">
						<view class="flex items-center justify-center mt-20 relative" @click="playAudio(item.voiceFile?.url)">
							<text class="text-26">{{item.soundmark}}</text>
							<view class="ml-10 absolute" style="right: -75rpx;">
								<c_trumpet :play="isPlayWord"/>
							</view>
						</view>
					</view>
				</template>
				<view class="flex flex-column items-center px-50 relative" style="padding-top: 210rpx;" v-else>
					
					<view class="flex items-center justify-center relative">
						<view
							class="px-100 text-center font-weight-700 relative" 
							:style="{'font-size': wordlist.length > 1 ? '48rpx': '80rpx'}" 
							@click="playAudio(item.voiceFile?.url)">
							<!-- {{item.word}} -->
							<template v-if="!/\s/.test(item.word)">
								{{item.word}}
							</template>
							<template v-else>
								<template v-if="item.sentencelist">
									<view 
										v-for="b,i in item.sentencelist"
										class="mr-10 inline-block relative" 
										:style="b.type ? 'margin: 0 16rpx 0 -6rpx;' : ''" 
										:class="{'text-red': (b.pronunciation < 95) && !b.type}"
									>
										{{b.word}}
									</view>
								</template>
								<text v-else>{{item.word}}</text>
							</template>
							<view class="ml-10" style="display: inline-block;" v-if="!item.soundmark">
								<c_trumpet :play="isPlayWord"/>
							</view>
						</view>
					</view>
					<view class="flex flex-column items-center" v-if="item.soundmark">
						<view class="flex items-center justify-center mt-20 relative" @click="playAudio(item.voiceFile?.url)">
							<text class="text-26">{{item.soundmark}}</text>
							<view class="ml-10 absolute" style="right: -75rpx;">
								<c_trumpet :play="isPlayWord"/>
							</view>
						</view>
					</view>
					
					<!-- <view class="py-10 flex items-center text-20 text-gray mt-100">
						流利度：
						<view class="jindubox"><view class="tag" :style="'width: '+(item.evaluation?.fluency || 0)+'%;'"></view></view>
						<text class="text-20 ml-20 text-gray" style="width: 60rpx;">{{parseInt(item.evaluation?.fluency) || 0}}%</text>
					</view>
					<view class="py-10 flex items-center text-20 text-gray">
						完整度：
						<view class="jindubox"><view class="tag" :style="'width: '+(item.evaluation?.completion || 0)+'%;'"></view></view>
						<text class="text-20 ml-20 text-gray" style="width: 60rpx;">{{parseInt(item.evaluation?.completion) || 0}}%</text>
					</view>
					<view class="py-10 flex items-center text-20 text-gray">
						准确度：
						<view class="jindubox"><view class="tag" :style="'width: '+(item.evaluation?.accuracy || 0)+'%;'"></view></view>
						<text class="text-20 ml-20 text-gray" style="width: 60rpx;">{{parseInt(item.evaluation?.accuracy) || 0}}%</text>
					</view>
					
					<view class="mt-50">
						<view class="flex flex-column items-center justify-center">
							<view class="text-50">
								{{parseInt(item.evaluation?.score) || 0}}<text class="text-22 font-weight-400 ml-5">分</text>
							</view>
						</view>
						<view class="mt-20 text-gray" style="border: 1px solid #94a19a; font-size: 20rpx; padding: 5rpx 10rpx; border-radius: 8rpx;">综合评分</view>
					</view> -->
					
					<view class="relative w-full mt-150">
						<view class="bgc-white w-full px-30 py-50 absolute" style="border-radius: 50rpx;" :class="{fadeInUp: item.answerFile}">
							<view class="flex items-center justify-center" style="margin-top: -100rpx;">
								<view style="transform: rotate(-15deg);">
									<image 
										:src="`${imgPath}png/${item.evaluation.accuracy < 30 ? 'star2' : 'star1'}.png`" 
										class="animate__bounceIn1" mode="widthFix" 
										style="height: 90rpx; width: 90rpx; "></image>
								</view>
								<view class="mx-20" style="transform: translateY(-14rpx); margin: 0 -10rpx;">
									<image 
										:src="`${imgPath}png/${item.evaluation.accuracy > 60 ? 'star1' : 'star2'}.png`" 
										class="animate__bounceIn1" mode="widthFix" 
										style="height: 100rpx; width: 100rpx; animation-delay: 0.1s;"></image>
								</view>
								<view style="transform: rotate(15deg);">
									<image 
										:src="`${imgPath}png/${item.evaluation.accuracy > 95 ? 'star1' : 'star2'}.png`" 
										class="animate__bounceIn1" mode="widthFix" 
										style="height: 90rpx; width: 90rpx; animation-delay: 0.2s;"></image>
								</view>
							</view>
							<view class="relative mt-30">
								<view class="text-28 text-center" v-if="item.evaluation.accuracy < 30">
									无效跟读，请重新录音！
								</view>
								<template v-else-if="item.evaluation.accuracy < 95">
									<view class="text-28 text-center">
										<view v-for="bb,i in item.evaluation?.analysis">
											<view style="font-size: 13px;" v-if="bb.pronunciation < 95">
												单词 {{bb.word}} 发音中的
												/
												<span style="display: inline-flex;">
													<template v-for="cc,s in bb.phonemes">
														<span :style="cc.pronunciation < 95 ? 'color: red' : ''">{{cc.phoneme}}</span>
													</template>
												</span>
												/
												发音不准确！
												<view>建议多多练习，巩固发音</view>
											</view>
										</view>
									</view>
								</template>
								<template v-else>
									<view class="text-28 text-center">非常棒!</view>
									<view class="text-28 text-center mt-5">再接再厉，继续加油</view>
								</template>
							</view>
							<!-- <view class="relative rd-6 mt-20" style="background-color: rgba(186, 186, 186, 0.1); padding: 30px 10px 20px;">
								<view class="absolute text-white text-24" style="position: absolute; left: 0; top: 0; background-color: #1CA498; padding: 4rpx 20rpx; border-radius: 6px 0;">单词问题</view>
								<view class="text-24" v-if="parseInt(item.evaluation.score) < 20">单词整体得分不到20分，初露锋芒，蓄势待发。这是每个旅程的开始，充满无限可能与希望。</view>
								<view class="text-24" v-if="parseInt(item.evaluation.score) >= 20 && parseInt(item.evaluation.score) < 40">单词整体得分不到40分，快速成长。在这个阶段，每一分努力都将加速你的进步与蜕变。</view>
								<view class="text-24" v-if="parseInt(item.evaluation.score) >= 40 && parseInt(item.evaluation.score) < 60">单词整体得分不到60分，稳健前行，面对挑战从容不迫。</view>
								<view class="text-24" v-if="parseInt(item.evaluation.score) >= 60 && parseInt(item.evaluation.score) < 80">单词整体得分已经大于60分了，每一份努力都汇聚成辉煌的成就，再接再厉，加油。</view>
								<view class="text-24" v-if="parseInt(item.evaluation.score) >= 80">单词整体得分已经大于80分了，达到巅峰，引领风骚。这是你成就与影响力的顶峰，继续照亮他人。</view>
							</view> -->
						</view>
					</view>
				</view>
				<view v-if="sentenceStatus" class="bgc-white round-md px-30 mx-50 py-30 mt-80">
					<view class="title">
						<text class="text-26">译文</text>
						<text class="title_tip w-30 h-30 round-full bgc-primary2" />
					</view>
					<view class="text-30 font-weight-700 mt-30">
						<view>{{item.translation}}</view>
					</view>
				</view>
			</view>
			<view class="px-50 pb-80 justify-between flex items-center text-48">
				<view class="spell spell-tishi w-100 h-100 bgc-white round-30 flex items-center justify-center" :style="{'color': sentenceStatus ? '#00c386' : '#333' }" @click="analysisEvent"></view>
				
				<view class="flex items-center justify-center flex-column relative" v-if="item.answerFile" >
					<view
						class="absolute w-100 h-100 bgc-white round-30 flex items-center justify-center" 
						style="left: 50%; top: -110rpx; white-space: nowrap; transform: translateX(-50%);"
						@click="item.answerFile = null"
					>
						<uni-icons type="refreshempty" color="#ff8523" size="44rpx" class="flex items-center"></uni-icons>
					</view>
					<view 
						class="w-100 h-100 bgc-white round-30 flex items-center relative justify-center text-30" 
						style="color: #00c386;"
						hover-class="botton-active"
						@click="mineplayMp3(item.answerFile?.url)">
						<view class="absolute" style="left: 45rpx; top: 25rpx; transform: scale(1.2);">
							<c_wifi :active="mineplayStatus"/>
						</view>
					</view>
				</view>
				<template v-else>
					<!-- #ifdef APP -->
					<c_nbvoicerecord :recordOptions="{format: 'amr', sampleRate: 16000}" :key="indexs" @startRecord="start" @endRecord="endRecord" />
					<!-- #endif -->
					<!-- #ifdef MP-WEIXIN -->
					<c_nbvoicerecord :recordOptions="{format: 'wav', sampleRate: 16000}" :key="indexs" @startRecord="start" @endRecord="endRecord" />
					<!-- #endif -->
				</template>
				<view class="w-100 h-100 bgc-white round-30 flex items-center relative justify-center text-30" @click="nextEvent(2)">
					<uni-icons type="arrow-right" size="44rpx" class="flex items-center"></uni-icons>
				</view>
			</view>
		</view>
	</view>
	<c_loading v-if="jisuanStatus"/>
</template>

<script setup>
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import c_trumpet from './trumpet.vue'
import c_wifi from './wifi.vue'
import useAudio from '../lib/useAudio'
import { postWordSpoken_api, selectWord_api, getYoudao_api, submitYoudao_api, audiowav_api } from '@/common/apis/spoken'
import { useCos } from '../lib/useCos'
import c_loading from './currentloading.vue'
import c_nbvoicerecord from './nb-voice-record.vue'
import { imgPath } from '@/common/config.js'

const { playAudio, isPlayWord, stopAudio } = useAudio()

const emit = defineEmits(['next', 'end'])

const props = defineProps({
	indexs: Number,
	item: Object,
	current: Number,
	logId: [Number, String]
})

watch(() => props.current, (newVal) => {
	if(newVal === props.indexs && newVal >= 0){
		playAudio(props.item.voiceFile.url)
	}
}, {immediate: true})

onBeforeUnmount(() => {
	stopAudio()
})

const itemWord = ref({})
const sentenceStatus = ref(false)
async function analysisEvent(){
	if(wordlist.value.length > 1){
		sentenceStatus.value = !sentenceStatus.value
	} else{
		uni.navigateTo({
			url: '/pages/course/spoken/translate?word=' + props.item.word
		})
	}
}

const wordlist = computed(() => {
	let res = props.item.word.split(/[\s,;]+/)
	console.log('JIEGUO', res, props.item.word)
	let text = "Hello World This Is A Test";
	let words = text.split(" ");
	console.log(222222, words);
	return props.item.word.split(' ')
})

const isRecord = ref(false)
const timer = ref(null)
const time = ref(0)
function start(){
	isRecord.value = true
	if(!timer.value){
		clearInterval(timer.value)
		timer.value = setInterval(() => {
			time.value = time.value + 1
		}, 1000)
	}
}

function nextEvent(type){
	if(isRecord.value && props.current === props.indexs){
		uni.showToast({
			title: '正在录音',
			icon: 'none'
		})
		return false
	}
	if(type === 2){
		emit('next', 'next')
	} else{
		emit('next', 'prev')
	}
}

/** pity mp3 */
const getPityMp3 = () => {
	let playSrc = '';
	
	playSrc = 'https://assets-1315727392.cos.ap-chongqing.myqcloud.com/YIYUAN/mp3/59f0493363e12.mp3';
	
	uni.useAudio.src(playSrc);
};

const getPityMp2 = () => {
	let playSrc = '';
	
	playSrc = 'https://assets-1315727392.cos.ap-chongqing.myqcloud.com/YIYUAN/mp3/59f0493363e12.mp3';
	
	uni.useAudio.src(playSrc);
};

/** success mp3 */
const getSuccessMp3 = () => {
	let playSrc = '';
	
	playSrc = 'https://assets-1315727392.cos.ap-chongqing.myqcloud.com/YIYUAN/mp3/59f0493363e12.mp3';
	
	uni.useAudio.src(playSrc);
};

const getBase64FromFile = (filePath) => {  
	return new Promise((resolve, reject) => {  
    plus.io.resolveLocalFileSystemURL(filePath, function(entry) {  
		entry.file(function(file) {  
			var reader = new plus.io.FileReader();  
			console.log(reader)
			reader.onloadend = function(e) {  
				var base64Data = e.target.result;  
				// console.log(base64Data)
				let base = base64Data.replace(/data:audio\/amr;base64,/, '')
				resolve(base)  
			};  
			reader.onerror = function(e) {  
				reject("读取文件失败：" + e.message);  
			};  
			reader.readAsDataURL(file);  
		}, function(e) {  
			reject("获取文件对象失败：" + e.message);  
		});  
    }, function(e) {  
		reject("解析文件路径失败：" + e.message);  
    });  
  });  
}  

const jisuanStatus = ref(false)
async function endRecord(data){
	jisuanStatus.value = true
	isRecord.value = false
	// #ifdef MP-WEIXIN
	const res = uni.getFileSystemManager().readFileSync(data.tempFilePath)
	const filewav = uni.arrayBufferToBase64(res)
	// #endif
	// #ifdef APP
	console.log(plus.io.convertLocalFileSystemURL(data.tempFilePath))
	const base64 = await getBase64FromFile(data.tempFilePath)
	// console.log(base64)
	let filewav = await audiowav_api({input: base64})
	// console.log(filewav)
	// #endif
	
	const first10 = filewav.slice(0, 10);
	const last10 = filewav.slice(-10);
	const input = first10 + filewav.length + last10
	const res1 = await getYoudao_api({input})
	uni.request({
		url: 'https://openapi.youdao.com/iseapi',
		method: 'POST',
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
		data: {
			q: filewav,
			text: props.item.word,
			langType: res1.langType,
			appKey: res1.appKey,
			salt: res1.salt,
			curtime: res1.curtime,
			sign: res1.sign,
			signType: res1.signType,
			format: 'wav',
			rate: 16000,
			channel: 1,
			type: 1
		},
		success: async (keyss) => {
			console.log('调用：', keyss)
			
			let result = keyss.data
			if(result.errorCode === '11010'){
				jisuanStatus.value = false
				uni.showToast({ title: '录音时间太短，请重录！', icon: 'none' })
				return false
			}
			if(['11301', '11302', '11303', '11304', '11411', '15003', '17005'].includes(result.errorCode)){
				jisuanStatus.value = false
				uni.showToast({ title: '网络错误，请稍后再试！', icon: 'none' })
				return false
			}
			jisuanStatus.value = false
			
			let obj = {
				score: result.overall,
				accuracy: result.pronunciation,
				fluency: result.fluency,
				completion: result.integrity,
				invalid: result.overall < 10 ? 1 : 0,
				analysis: result.words || [],
			}
			let obj2 = {
				fluency: result.fluency,
				accuracy: result.pronunciation,
				completion: result.integrity
			}
			
			let regex = /[\w']+|[,!]/g;
			let matches = props.item.word.match(regex)
			let temparr = [], newArr = JSON.parse(JSON.stringify(result.words))
			for (let i = 0; i < matches.length; i++) {  
			    const bb = matches[i]
			    if (bb.match(/[\s,!]+/)) {
					newArr.splice(i, 0, {word: bb, type: 1})
			    }
			}
			
			emit('end', {
				...props.item,
				sentencelist: newArr,
				evaluation: obj,
				suggestion: obj2,
				answerFile: {},
				indexs: props.indexs
			})
			if(result.pronunciation > 95){
				getSuccessMp3()
			} else if(result.pronunciation > 60){
				getPityMp2()
			}else{
				getPityMp3()
			}
			
			// #ifdef APP
			const { cosdata, str, cosapi, resdata } = await useCos(plus.io.convertLocalFileSystemURL(data.tempFilePath))
			// #endif
			// #ifdef MP-WEIXIN
			const { cosdata, str, cosapi, resdata } = await useCos(data.tempFilePath)
			// #endif
			
			let answerFile = {
				path: str,
				url: 'https://' + resdata.Location
			}
			let obj3 = {
				exerciseId: props.logId,
				vocabularyId: props.item.id,
				useTime: time.value,
				answerFile: str,
				evaluation: obj,
				suggestion: obj2
			}
			clearInterval(timer.value)
			submitYoudao_api(obj3).then(res => {
				emit('end', {
					...props.item,
					answerFile: answerFile,
					indexs: props.indexs
				})
			})
		},
		error: (err) => {
			console.log(err)
			jisuanStatus.value = false
			uni.showToast({ title: '网络错误，请稍后再试！', icon: 'none' })
		}
	})
}

const innerAudioContext = uni.createInnerAudioContext()
	
const mineplayStatus = ref(false)

innerAudioContext.onStop(() => {
	mineplayStatus.value = false
})
innerAudioContext.onEnded(() => {
	mineplayStatus.value = false
})
innerAudioContext.onPlay(() => {
	console.log('音乐开始播放')
})

function mineplayMp3(url){
	if(!mineplayStatus.value){
		mineplayStatus.value = true
		innerAudioContext.autoplay = true;
		innerAudioContext.src = url
		innerAudioContext.play()
	} else{
		mineplayStatus.value = false
		innerAudioContext.stop()
	}
}
</script>

<style lang="scss" scoped>
.jindubox{
	border-radius: 50rpx;
	flex: 1;
	min-width: 0;
	background-color: #f5f5f5;
	overflow: hidden;
	position: relative;
	height: 8rpx;
	.tag{
		width: 0;
		height: 100%;
		background-color: $primary;
		border-radius: 50rpx;
	}
}

.title {
	position: relative;
	.title_tip {
		position: absolute;
		top: 0;
		left: 0;
		transform: translate(-8rpx, 0);
		opacity: .2;
	}
}

@keyframes fadeInUp {  
  from {  
    opacity: 0; /* 初始透明度为0 */  
    transform: translateY(30px); /* 初始位置向下偏移30px */  
  }  
  to {  
    opacity: 1; /* 透明度变为1，即完全可见 */  
    transform: translateY(0); /* 回到原始位置 */  
  }  
}  
.fadeInUp {  
  animation-name: fadeInUp; /* 应用上面定义的关键帧动画 */  
  animation-duration: 0.5s; /* 动画持续时间 */  
  animation-fill-mode: both; /* 动画完成后保持最后一帧的状态 */  
  /* 可以根据需要添加更多动画属性，如animation-timing-function等 */  
}
@keyframes bounceIn {
	  from,
	  20%,
	  40%,
	  60%,
	  80%,
	  to {
	    -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
	    animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
	  }
	
	  0% {
	    opacity: 0;
	    -webkit-transform: scale3d(0.3, 0.3, 0.3);
	    transform: scale3d(0.3, 0.3, 0.3);
	  }
	
	  20% {
	    -webkit-transform: scale3d(1.1, 1.1, 1.1);
	    transform: scale3d(1.1, 1.1, 1.1);
	  }
	
	  40% {
	    -webkit-transform: scale3d(0.9, 0.9, 0.9);
	    transform: scale3d(0.9, 0.9, 0.9);
	  }
	
	  60% {
	    opacity: 1;
	    -webkit-transform: scale3d(1.03, 1.03, 1.03);
	    transform: scale3d(1.03, 1.03, 1.03);
	  }
	
	  80% {
	    -webkit-transform: scale3d(0.97, 0.97, 0.97);
	    transform: scale3d(0.97, 0.97, 0.97);
	  }
	
	  to {
	    opacity: 1;
	    -webkit-transform: scale3d(1, 1, 1);
	    transform: scale3d(1, 1, 1);
	  }
	}
	.animate__bounceIn1 {
		opacity: 0;
		animation-duration: calc(1s * 0.75);
		animation-name: bounceIn;
		animation-delay: 0s;
		animation-fill-mode: forwards;
	}
</style>